import { fetch } from "@tauri-apps/plugin-http"
import {
    IObserverAircraftDataResponse,
    IObserverAircraftDataResponseUnit
} from "./interfaces/IObserverAircraftDataResponse";
import { error } from "@tauri-apps/plugin-log";

export async function getVatsimPilotsOfAirports(...airports: string[]): Promise<IObserverAircraftDataResponse> {
    try {
        const param = airports.map(code => code.trim()).join(",");
        const response = await fetch(`https://api.aviationapi.com/v1/vatsim/pilots?apt=${param}`, { method: 'GET' });
        const jsonTarget = await response.json();
        let result: IObserverAircraftDataResponse = [];
        for (const airport of Object.entries(jsonTarget)) {
            const unit: IObserverAircraftDataResponseUnit = {
                airport: airport[0],
                arrivals: (airport[1] as any).Arrivals,
                departures: (airport[1] as any).Departures
            }
            result.push(unit);
        }
        return result;
    } catch (e: any) {
        await error(e);
        return [];
    }
}

